import React from 'react';
import { Collapse, Button, Tag, Space, Typography, Spin, Empty } from 'antd';
import { LineChartOutlined, ReloadOutlined, BarChartOutlined } from '@ant-design/icons';
import { ExperimentDataSeries, ExperimentDataCategory } from '../../types';
import ChartViewer from '../charts/ChartViewer';
import { ChartViewMode } from '../charts/types';
import { useVisualization } from '../../contexts/VisualizationContext';

const { Title, Paragraph, Text } = Typography;

interface SeriesDataSectionProps {
  seriesData: ExperimentDataSeries[];
  experimentId: number;
  experimentName?: string;
  category: ExperimentDataCategory;
  seriesDataMap: Record<number, {
    loading: boolean;
    data: any[];
    columns: Array<{ name: string; type: string }>;
    totalRows: number;
    currentPage: number;
    pageSize: number;
    hasMore: boolean;
  }>;
  getSeriesViewMode: (seriesId: number) => ChartViewMode;
  updateSeriesViewMode: (seriesId: number, updates: Partial<ChartViewMode>) => void;
  onLoadSeriesData: (seriesId: number, page?: number, pageSize?: number) => void;
  onSeriesExpand: (seriesIds: (string | number)[]) => void;
  expandedSeriesKeys?: (string | number)[];
}

const SeriesDataSection: React.FC<SeriesDataSectionProps> = ({
  seriesData,
  experimentId,
  experimentName,
  category,
  seriesDataMap,
  getSeriesViewMode,
  updateSeriesViewMode,
  onLoadSeriesData,
  onSeriesExpand,
  expandedSeriesKeys = [],
}) => {
  const { 
    addVisualizationItem, 
    removeVisualizationItem, 
    isItemVisualized,
    getVisualizationItemId
  } = useVisualization();

  if (!seriesData || seriesData.length === 0) {
    return null;
  }

  const collapseItems = seriesData.map((series) => {
    const seriesDataState = seriesDataMap[series.id];
    const columns = (seriesDataState?.columns && Array.isArray(seriesDataState.columns))
      ? seriesDataState.columns
      : [];
    const tableColumns = columns.map(col => ({
      title: col.name,
      dataIndex: col.name,
      key: col.name,
      render: (text: any) => {
        if (text === null || text === undefined) {
          return <Text type="secondary">-</Text>;
        }
        if (typeof text === 'number') {
          return text.toLocaleString();
        }
        return String(text);
      }
    }));

    return {
      key: String(series.id),
      label: (
        <Space>
          <Text strong>{series.name}</Text>
          {series.unit && <Tag>{series.unit}</Tag>}
          {series.data_group && (
            <Tag color="purple">{series.data_group}</Tag>
          )}
          <Tag color="green">长度: {series.data_length}</Tag>
          {seriesDataState && seriesDataState.data && (
            <Tag color="blue">
              已加载 {seriesDataState.data.length} / {seriesDataState.totalRows}
            </Tag>
          )}
        </Space>
      ),
      extra: (
        <Space>
          <Button
            type={isItemVisualized(experimentId, series.id) ? "primary" : "default"}
            size="small"
            icon={<BarChartOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              if (isItemVisualized(experimentId, series.id)) {
                // 如果已添加，则移除
                const itemId = getVisualizationItemId(experimentId, category.id, series.id);
                removeVisualizationItem(itemId);
              } else {
                // 如果未添加，则添加
                addVisualizationItem(experimentId, experimentName, category, series);
              }
            }}
          >
            {isItemVisualized(experimentId, series.id) ? '已添加' : '可视化'}
          </Button>
          {seriesDataState?.loading ? (
            <Spin size="small" />
          ) : (
            <Button
              type="link"
              size="small"
              icon={<ReloadOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                onLoadSeriesData(series.id, seriesDataState?.currentPage || 1);
              }}
            >
              刷新
            </Button>
          )}
        </Space>
      ),
      children: (
        <div>
          <div style={{ marginBottom: 12 }}>
            {series.description && (
              <Paragraph style={{ marginBottom: 8, fontSize: '12px', color: '#999' }}>
                {series.description}
              </Paragraph>
            )}
          </div>

          {seriesDataState && seriesDataState.data && Array.isArray(seriesDataState.data) ? (
            <ChartViewer
              data={seriesDataState.data}
              columns={seriesDataState.columns}
              axisConfig={{
                xAxis: getSeriesViewMode(series.id).xAxis,
                yAxis: getSeriesViewMode(series.id).yAxis,
              }}
              displayMode={getSeriesViewMode(series.id).mode}
              chartType={getSeriesViewMode(series.id).chartType}
              title={series.name || '数据图表'}
              onDisplayModeChange={(mode) => updateSeriesViewMode(series.id, { mode })}
              onChartTypeChange={(chartType) => updateSeriesViewMode(series.id, { chartType })}
              tableColumns={tableColumns}
              tableDataSource={seriesDataState.data.map((row, index) => ({
                ...row,
                key: index
              }))}
              loading={seriesDataState.loading}
              pagination={{
                current: seriesDataState.currentPage,
                pageSize: seriesDataState.pageSize,
                total: seriesDataState.totalRows,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`,
                onChange: (page, pageSize) => {
                  onLoadSeriesData(series.id, page, pageSize);
                },
                onShowSizeChange: (current, size) => {
                  onLoadSeriesData(series.id, 1, size);
                }
              }}
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Empty description="点击展开查看数据" />
            </div>
          )}
        </div>
      )
    };
  });

  return (
    <div>
      <Title 
        level={5} 
        style={{ 
          marginTop: 0, 
          marginBottom: 16, 
          fontWeight: 500,
          fontSize: '15px',
          color: '#595959'
        }}
      >
        <LineChartOutlined style={{ marginRight: 8 }} /> 
        序列数据
      </Title>
      <Collapse
        style={{ marginTop: 16 }}
        activeKey={expandedSeriesKeys}
        onChange={(keys) => {
          onSeriesExpand(keys);
        }}
        items={collapseItems.map(item => ({
          ...item,
          children: (
            <div data-series-id={item.key} key={item.key}>
              {item.children}
            </div>
          )
        }))}
      />
    </div>
  );
};

export default SeriesDataSection;

